﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Navigation;
using GTasks;
using GTasksPlus.Code;
using GTasksPlus.Model;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;

namespace GTasksPlus.Views
{
    public partial class Manipulate
    {
        private static string _id = String.Empty;
        private static string _listId = String.Empty;

        public Manipulate()
        {
            if (IsLoggedIn())
                InitializeComponent();
            else
                NavigationService.Navigate(new Uri("/Login.xaml", UriKind.RelativeOrAbsolute));
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ApplicationTitle.Text = GTasksSettings.ApplicationTitle;
            if (e.NavigationMode == NavigationMode.New)
            {
                AddUpdateButton();
                _id = NavigationContext.QueryString.ContainsKey("Id")
                          ? NavigationContext.QueryString["Id"]
                          : String.Empty;
                _listId = NavigationContext.QueryString.ContainsKey("List")
                              ? NavigationContext.QueryString["List"]
                              : String.Empty;
                if (!_id.Equals("new"))
                {
                    var s = from p in App.TaskViewModel.TaskItem
                            where p.id == _id
                            select p;
                    var taskItem = s.SingleOrDefault();
                    if (taskItem != null)
                    {
                        Title.Text = taskItem.title;
                        Notes.Text = taskItem.notes ?? String.Empty;
                        if (!string.IsNullOrEmpty(taskItem.due))
                        {
                            reminderCheckBox.IsChecked = true;
                            reminderDate.Value = DateTime.Parse((taskItem.due)).Date;
                            timePicker.Value = GetExistingReminder();
                            timePicker.Visibility = reminderDate.Visibility = Visibility.Visible;
                        }
                        else
                            timePicker.Visibility = reminderDate.Visibility = Visibility.Collapsed;
                    }
                    AddReminderButton();
                    AddDeleteButton();
                }
                else
                {
                    PageTitle.Text = PageTitle.Text.Replace("edit", "add");
                }
            }
        }

        private void GetResponse(bool obj)
        {
            performanceProgressBar.Visibility = Visibility.Collapsed;
            NavigationService.Navigate(new Uri("/Views/TaskView.xaml?Id=" + _listId, UriKind.RelativeOrAbsolute));
        }

        private void GetResponseNoNavigation(bool obj)
        {
            performanceProgressBar.Visibility = Visibility.Collapsed;
        }

        #region Adding Buttons
        private void AddReminderButton()
        {
            var reminderButton = new ApplicationBarIconButton { Text = "Reminder", IconUri = new Uri("/Images/alarmclock.png", UriKind.Relative) };
            reminderButton.Click += ReminderClick;
            if (ApplicationBar.Buttons.IndexOf(reminderButton) < 0)
                ApplicationBar.Buttons.Add(reminderButton);
        }

        private void AddDeleteButton()
        {
            var deleteButton = new ApplicationBarIconButton { Text = "Delete", IconUri = new Uri("/Images/delete.png", UriKind.Relative) };
            deleteButton.Click += DeleteClick;
            if (ApplicationBar.Buttons.IndexOf(deleteButton) < 0)
                ApplicationBar.Buttons.Add(deleteButton);
        }

        private void AddUpdateButton()
        {
            var updateButton = new ApplicationBarIconButton { Text = "Save", IconUri = new Uri("/Images/save.png", UriKind.Relative) };
            updateButton.Click += UpdateClick;
            if (ApplicationBar.Buttons.IndexOf(updateButton) < 0)
                ApplicationBar.Buttons.Add(updateButton);
        } 
        #endregion

        #region Click Handlers
        private void DeleteClick(object sender, EventArgs eventArgs)
        {
            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;
            ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = false;
            performanceProgressBar.Visibility = Visibility.Visible;
            var s = from p in App.TaskViewModel.TaskItem
                    where p.id == _id
                    select p;
            s.Single().Delete(GetResponse);
        }

        private void ReminderClick(object sender, EventArgs e)
        {
            SaveTask(GetResponseNoNavigation);
            if (!string.IsNullOrEmpty(GetReminderDateTimeForSaving()))
            {
                var reminder = new Reminder(Title.Text.Trim())
                {
                    RecurrenceType = RecurrenceInterval.None,
                    Title = Title.Text.Trim().Substring(0, Title.Text.Trim().Length > 63 ? 62 : Title.Text.Trim().Length),
                    Content = Notes.Text.Trim(),
                    BeginTime = GetReminderDateTime(),
                    NavigationUri = new Uri(String.Format("/Views/TaskView.xaml?Id={0}&TaskId={1}", _listId, _id), UriKind.RelativeOrAbsolute)
                };
                var message = String.Format("reminder for {0} at {1}", reminder.Title, GetReminderDateTime());
                var result = MessageBox.Show("Do you want to add the " + message + "?", reminder.Title, MessageBoxButton.OKCancel);
                if (result.CompareTo(MessageBoxResult.OK) == 0 && (GetReminderDateTime().Ticks > DateTime.Now.Ticks))
                {
                    if (!ReminderAlreadyExists())
                        ScheduledActionService.Add(reminder);
                    else
                    {
                        var oldReminder = GetReminderWhichAlreadyExists();
                        oldReminder.BeginTime = reminder.BeginTime;
                        oldReminder.Content = reminder.Content;
                        oldReminder.Title = reminder.Title;
                        oldReminder.NavigationUri = reminder.NavigationUri;
                        ScheduledActionService.Replace(oldReminder);
                    }
                    MessageBox.Show("The " + message + " has been added successfully.", reminder.Title, MessageBoxButton.OK);
                }
            }
        }

        private void UpdateClick(object sender, EventArgs e)
        {
            SaveTask(GetResponse);
        }

        private void reminderCheckBox_Click(object sender, RoutedEventArgs e)
        {
            if (reminderCheckBox.IsChecked != null && (bool)reminderCheckBox.IsChecked)
                timePicker.Visibility = reminderDate.Visibility = Visibility.Visible;
            else
                timePicker.Visibility = reminderDate.Visibility = Visibility.Collapsed;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            while (NavigationService.CanGoBack)
                NavigationService.RemoveBackEntry();
            NavigationService.Navigate(new Uri("/Views/TaskView.xaml?Id=" + _listId, UriKind.RelativeOrAbsolute));
        }
        #endregion

        private void SaveTask(Action<bool> response)
        {
            if (!string.IsNullOrEmpty(Title.Text.Trim()))
            {
                ((ApplicationBarIconButton) ApplicationBar.Buttons[0]).IsEnabled = false;
                performanceProgressBar.Visibility = Visibility.Visible;
                if (!_id.Equals("new"))
                {
                    ((ApplicationBarIconButton) ApplicationBar.Buttons[2]).IsEnabled = false;
                    var s = from p in App.TaskViewModel.TaskItem
                            where p.id == _id
                            select p;
                    var taskItem = s.First();
                    taskItem.title = Title.Text.Trim();
                    if (!string.IsNullOrEmpty(Notes.Text.Trim()))
                        taskItem.notes = Notes.Text.Trim();
                    taskItem.due = GetReminderDateTimeForSaving();
                    taskItem.Update(response);
                }
                else
                {
                    var t = new TaskItem
                                {
                                    title = Title.Text.Trim(),
                                    notes = Notes.Text.Trim(),
                                    due = GetReminderDateTimeForSaving()
                                };
                    TaskHelper.AddTask(t, response, _listId);
                }
            }
        }

        private string GetReminderDateTimeForSaving()
        {
            string dateVal = String.Empty, timeVal = String.Empty;
            if (reminderCheckBox.IsChecked == true && reminderDate.Value != null && timePicker.Value != null)
            {
                dateVal = ((DateTime)reminderDate.Value).ToString("yyyy-MM-dd'T'");
                timeVal = ((DateTime)timePicker.Value).ToString("HH:mm:ss.000Z");
            }
            return dateVal + timeVal;
        }

        private DateTime GetReminderDateTime()
        {
            string dateVal = String.Empty, timeVal = String.Empty;
            if (reminderCheckBox.IsChecked == true && reminderDate.Value != null && timePicker.Value != null)
            {
                dateVal = ((DateTime)reminderDate.Value).ToString("yyyy-MM-dd ");
                timeVal = ((DateTime)timePicker.Value).ToString("HH:mm");
            }
            return Convert.ToDateTime(dateVal + timeVal);
        }

        public DateTime GetExistingReminder()
        {
            var allReminders = ScheduledActionService.GetActions<Reminder>();
            foreach (var reminder in allReminders)
            {
                if (reminder.NavigationUri.ToString().Contains(_id))
                    return reminder.BeginTime;
            }
            return DateTime.Now.ToLocalTime();
        }

        public bool ReminderAlreadyExists()
        {
            var allReminders = ScheduledActionService.GetActions<Reminder>();
            return allReminders.Any(reminder => reminder.NavigationUri.ToString().Contains(_id));
        }

        public Reminder GetReminderWhichAlreadyExists()
        {
            var allReminders = ScheduledActionService.GetActions<Reminder>();
            return allReminders.SingleOrDefault(reminder => reminder.NavigationUri.ToString().Contains(_id));
        }
    }
}